package cn.com.controller.wxController;

import java.math.BigDecimal;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;

import cn.com.constant.Code;
import cn.com.db.model.DiyOrder;
import cn.com.db.model.Order;
import cn.com.db.model.WxDiyPayResult;
import cn.com.db.model.WxDiyRefundResult;
import cn.com.db.model.WxPayResult;
import cn.com.db.model.WxRefundResult;
import cn.com.db.service.DiyOrderService;
import cn.com.db.service.OrderService;
import cn.com.db.service.WxDiyPayResultService;
import cn.com.db.service.WxDiyRefundResultService;
import cn.com.db.service.WxPayResultService;
import cn.com.db.service.WxRefundResultService;
import cn.com.util.DataResult;
import cn.com.util.JsonUtil;
import cn.com.util.TimeUtil;
import cn.com.util.UidUtil;
import cn.com.wxUtil.XMLUtil;
import cn.com.wxUtil.wxConstant;
import cn.com.wxUtil.refundUtil.WeiXinAtcion;

/**
 * 退款
 * @author mxq
 */
@RestController
@RequestMapping("/wx/")
public class RefundController {

		@Autowired
		OrderService orderService;
		@Autowired
		WxPayResultService wxPayResultService;
		@Autowired
		WxDiyPayResultService wxDiyPayResultService;
		@Autowired
		DiyOrderService diyOrderService;
		@Autowired
		WxRefundResultService wxRefundResultService;
		@Autowired
		WxDiyRefundResultService wxDiyRefundResultService;
		
		@RequestMapping(value = "refund")
		public String refund(HttpServletRequest request, HttpServletResponse response,
				@RequestParam("orderId")String order_id
				) throws Exception {
			DataResult dataResult = new DataResult();
			
			Order order = orderService.getOrderById(order_id);
			
			WxPayResult payResult = wxPayResultService.getPayResultByOrderId(order_id);
			String out_trade_no = payResult.getId(); // 退款订单
			String xmlWxInfo = payResult.getWx_meta_info();
			Map xmlMap = XMLUtil.doXMLParse(xmlWxInfo);
			String total_fee = (String) xmlMap.get("cash_fee");
			BigDecimal all_total_fee = new BigDecimal(total_fee); // 订单金额
			BigDecimal refund_fee = order.getPrice().movePointRight(2); // 退款金额
			String appid = wxConstant.APPID; // 微信小程序--》“开发者ID”
			String mch_id = wxConstant.MCH_ID; // 商户号，将该值赋值给partner
			String key = wxConstant.PAY_KEY; // 微信支付商户平台登录）--》“API安全”--》“API密钥”--“设置密钥”（设置之后的那个值就是partnerkey，32位）

			Map<String, String> refundmap = WeiXinAtcion.wechatRefund(mch_id, appid, key, out_trade_no, all_total_fee,
					refund_fee);
			
			@SuppressWarnings("unused")
			String resultJson = JSON.toJSONString(refundmap);
			// 退款之后业务逻辑 : 修改订单状态,新建数据库表
			if (refundmap.get("return_code").equals("SUCCESS")) {
				if (refundmap.get("result_code").equals("FAIL")) {
					// 失败
					dataResult.setData(refundmap.get("err_code_des"));
					dataResult.setCode(Code.REFUND_FAIL);
					dataResult.setMessage("退款失败");
					return JsonUtil.toJsonString(dataResult);
				} else {
					WxRefundResult wxRefundResult = new WxRefundResult();
					wxRefundResult.setId(UidUtil.createUUID());
					wxRefundResult.setOrder(order_id);
					wxRefundResult.setSeller(order.getSeller());
					wxRefundResult.setUser(order.getUser());
					wxRefundResult.setStore(order.getStore());
					wxRefundResult.setWx_meta_info(resultJson);    // 存的json
					wxRefundResult.setCreated_at(TimeUtil.getNowTimestamp());
					wxRefundResult.setUpdated_at(TimeUtil.getNowTimestamp());
					wxRefundResultService.createRefundResult(wxRefundResult);
					
					dataResult.setData(order_id);
					dataResult.setCode(Code.SUCCESS);
					dataResult.setMessage("退款成功");
					return JsonUtil.toJsonString(dataResult);
				}
			} else {
				// 失败
				dataResult.setData(refundmap.get("return_ms"));
				dataResult.setCode(Code.REFUND_FAIL);
				dataResult.setMessage("退款请求失败");
				return JsonUtil.toJsonString(dataResult);
			}
		}
		
		@RequestMapping(value = "refundDiyOrder")
		public String refundDiyOrder(HttpServletRequest request, HttpServletResponse response,
				@RequestParam("orderId")String order_id
				) throws Exception {
			DataResult dataResult = new DataResult();
			
			DiyOrder order = diyOrderService.getDiyOrderById(order_id);
			
			WxDiyPayResult payResult = wxDiyPayResultService.getPayResultByOrderId(order_id);
			String out_trade_no = payResult.getId(); // 退款订单
			String xmlWxInfo = payResult.getWx_meta_info();
			Map xmlMap = XMLUtil.doXMLParse(xmlWxInfo);
			String total_fee = (String) xmlMap.get("cash_fee");
			BigDecimal all_total_fee = new BigDecimal(total_fee); // 订单金额
			BigDecimal refund_fee = order.getPrice().movePointRight(2); // 退款金额
			String appid = wxConstant.APPID; // 微信小程序--》“开发者ID”
			String mch_id = wxConstant.MCH_ID; // 商户号，将该值赋值给partner
			String key = wxConstant.PAY_KEY; // 微信支付商户平台登录）--》“API安全”--》“API密钥”--“设置密钥”（设置之后的那个值就是partnerkey，32位）

			Map<String, String> refundmap = WeiXinAtcion.wechatRefund(mch_id, appid, key, out_trade_no, all_total_fee,
					refund_fee);
			@SuppressWarnings("unused")
			String resultJson = JSON.toJSONString(refundmap);
			// 退款之后业务逻辑 : 修改订单状态,新建数据库表
			if (refundmap.get("return_code").equals("SUCCESS")) {
				if (refundmap.get("result_code").equals("FAIL")) {
					// 失败
					dataResult.setData(refundmap.get("err_code_des"));
					dataResult.setCode(Code.REFUND_FAIL);
					dataResult.setMessage("退款失败");
					return JsonUtil.toJsonString(dataResult);
				} else {
					
					WxDiyRefundResult wxRefundResult = new WxDiyRefundResult();
					wxRefundResult.setId(UidUtil.createUUID());
					wxRefundResult.setOrder(order.getId());
					wxRefundResult.setSeller(order.getSeller());
					wxRefundResult.setUser(order.getUser());
					wxRefundResult.setStore(order.getStore());
					wxRefundResult.setWx_meta_info(resultJson);  // 存json
					wxRefundResult.setCreated_at(TimeUtil.getNowTimestamp());
					wxRefundResult.setUpdated_at(TimeUtil.getNowTimestamp());
					wxDiyRefundResultService.createDiyRefundResult(wxRefundResult);
					
					dataResult.setData(order_id);
					dataResult.setCode(Code.SUCCESS);
					dataResult.setMessage("退款成功");
					return JsonUtil.toJsonString(dataResult);
				}
			} else {
				// 失败
				dataResult.setData(refundmap.get("return_ms"));
				dataResult.setCode(Code.REFUND_FAIL);
				dataResult.setMessage("退款请求失败");
				return JsonUtil.toJsonString(dataResult);
			}
		}
	}

